<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Range implements Rule
{

    protected $type;
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($type = 'integer')
    {
        $this->type = $type;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  array|string  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $args = is_array($value) ? $value : explode(',', $value);
        if (count($args) !== 2)
            return false;
        $from = $args[0];
        $to =  $args[1];
        switch ($this->type) {
            case 'integer':
                if (!is_numeric($from) || !is_numeric($to) || $from > $to)
                    return false;
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute illegal range pattern, should be like A,B and A,B must be type of '.$this->type;
    }
}
